package com.gy.smart.util;

import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 作者：gy on 17/1/8
 * 说明：
 */
public class ChangeSign {

    public static String getSign(RequestParams params) {
        String sign = "MjAxN1/npL7ljLrkuYvnqpc=";
        List<KeyValue> list = params.getStringParams();
        List<String> keys = new ArrayList<>();
        List<String> valus = new ArrayList<>();
        for (KeyValue key : list) {
            keys.add(key.key);
//            valus.add((String) key.value);
        }
        Collections.sort(keys);
        for (String str : keys) {
            valus.add(params.getStringParameter(str));
            sign += str+params.getStringParameter(str);
        }
        LogUtil.e(sign);
        try {
            sign = getMD5(sign);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sign;
    }

    public static String getMD5(String val) throws NoSuchAlgorithmException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(val.getBytes());
        byte[] m = md5.digest();//加密
        return getString(m);
    }

    private static String getString(byte[] b) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            int a = b[i];
            if (a < 0)
                a += 256;
            if (a < 16)
                buf.append("0");
            buf.append(Integer.toHexString(a));

        }
        return buf.toString();
    }
}
